package programer.interviewer.link;

public class Question14 {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {

        ListNode resNode = new ListNode(0);
        ListNode curNode = resNode;
        int l1Value,l2Value,num,factor=0;

        while (l1 != null || l2 != null) {
            l1Value = l1 == null? 0: l1.val;
            l2Value = l2 == null? 0: l2.val;

            num = l1Value + l2Value + factor;
            factor = num / 10;
            curNode.next = new ListNode(num % 10);
            if (l1 != null) {
                l1 = l1.next;
            }

            if (l2 != null) {
                l2 = l2.next;
            }

            curNode = curNode.next;
        }

        if (factor != 0) {
            curNode.next = new ListNode(factor);
        }
        LinkUtil.printfLink(resNode.next);
        return resNode.next;
    }

    public static void main(String[] args) {
        new Question14().addTwoNumbers(LinkUtil.createLinkList(new int[] {7,1,6}),LinkUtil.createLinkList(new int[] {5,9,5}));
    }
}
